package cn.tedu.blog.server.controller.system;

import cn.tedu.blog.server.exception.ServiceException;
import cn.tedu.blog.server.mapper.UserMapper;
import cn.tedu.blog.server.sms.SmsClient;
import cn.tedu.blog.server.utils.CacheUtils;
import cn.tedu.blog.server.utils.ServiceCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 短信Controller
 */
@RestController
@RequestMapping("/sms")
public class SmsController {

    @Autowired
    private SmsClient smsClient;
    @Autowired
    private UserMapper userMapper;
    @GetMapping("/sendSmsCode")
    public Map<String, Object> sendSmsCode(@RequestParam("phoneNumber") String phoneNumber) {
        System.out.println("接收到的号码："+phoneNumber);

//        if (userMapper.isPhone(phoneNumber)>0){
//            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"【"+phoneNumber+"】不存在，点我前往注册");
//        }
        Map<String, Object> result = new HashMap<>();
        //生成四位随机数验证码
        String smsCode = (int) ((Math.random() * 9 + 1) * 1000) + "";
        try {
            smsClient.sendSmsCode(phoneNumber, smsCode);
            //发送短信成功，将生成的短信验证码存入本地缓存，后续用于效验
            CacheUtils.putCache(phoneNumber, smsCode);
            result.put("code", 1);
            result.put("msg", "短信发送成功");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.put("code", 2);
        result.put("msg", "短信发送失败");
        return result;
    }

    @GetMapping("/checkSmsCode")
    public Map<String, Object> checkSmsCode( @RequestParam("phoneNumber") String phoneNumber, @RequestParam("smsCode") String smsCode) {
        Map<String, Object> result = new HashMap<>();
        String cacheCode = CacheUtils.getCache(phoneNumber);
        System.out.println("用户传来的短信码:" + smsCode);
        System.out.println("缓存中的短信码:" + cacheCode);
        //验证短信码
        if (cacheCode !=null && cacheCode.equals(smsCode)) {
            //如果短信验证码正确，先删除缓存，做令牌清除
//            CacheUtils.deleteCache(phoneNumber);
            result.put("code", 1);
            result.put("msg", "效验短信码成功");
            return result;
        }
        result.put("code", 2);
        result.put("msg", "效验短信码失败");
        return result;
    }
}
